//
//  BluetoothManager.swift
//  Nokia
//
//  Created by 醉舞 on 2022/4/22.
//

import Foundation
import CoreBluetooth
import HandyJSON
import MYModule
import CRPSmartRing


public final class BluetoothManager: NSObject {
    
    
    public static let shared = BluetoothManager()
    
    // 用于获取已经连接设备
    //    var centralManager: CBCentralManager?
    
    /// 当前连接的设备信息
    public var connectDiscovery: CRPDiscovery?
    
    /// 当前设备的久坐提醒信息
    public var deviceReminderModel: CRPSmartRing.CRPActivityReminderModel?
    
    public var deviceState: CRPState = .disconnected
    
    public var bluetoothState: CRPBluetoothState = .unknown
    
    /// 当前电量，0是无效值
    public var currentBattery: Int?
    
    /// 是否在充电
    public var isBatterycharging: Bool {
        
        guard let currentBattery = currentBattery else {
            return false
        }
        return currentBattery > 100
        
    }
    
    /// 是否佩戴的（）
    public var wearState: Bool = false
    
    /// 正在测量类型（注意： 当有一类开启测量，上一次的未结束测量要强制结束）
    public var measuring: MeasureType = .none {
        
        didSet {
            
            if measuring != oldValue {
                
                NotificationCenter.default.post(name: .kReceiveMeasuringNotification, object: nil, userInfo: ["result": measuring])
                
            }
            
        }
        
    }
    
   
    fileprivate var timer: Timer?
    
    // 上一次同步戒指的时间
    fileprivate var updateDateTimer: Double = 0
    
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
   
    private override init() {
        super.init()
        
        // 进入前台发送通知
        NotificationCenter.default.addObserver(self, selector: #selector(setTime), name: UIApplication.willEnterForegroundNotification, object: nil)
        
        addTime()
        
    }
    
    
    public func addTime() {
        
        let timer = Timer.scheduledTimer(withTimeInterval: 2 * 3600, repeats: true, block: {[weak self] _ in
            
            guard let self = self else { return }
            self.updateTime()
        })
        
        RunLoop.current.add(timer, forMode: .common)
        self.timer = timer
        
    }
    

    
    public func setBluetoothConfig() {
        CRPSmartRingSDK.sharedInstance.delegate = self
    }
    
    public func isConnectedForConnectState(closure: @escaping () -> ()) {
        guard self.deviceState == .connected else {
            return
        }
        closure()
    }
    
    public func isPoweredOnForBluetoothState(closure: @escaping () -> ()) {
        guard self.bluetoothState == .poweredOn else {
            return
        }
        closure()
    }
    
    
    /// 扫描
    /// - Parameters:
    ///   - duration: 时长
    ///   - progressHandler:
    ///   - completionHandler:
    public func scan(_ duration: TimeInterval = 3, progressHandler: CRPSmartRing.scanProgressHandler?, completionHandler: CRPSmartRing.scanCompletionHandler?){
        self.isPoweredOnForBluetoothState {
            CRPSmartRingSDK.sharedInstance.scan(duration) { newDiscoveries in
                progressHandler?(newDiscoveries)
            } completionHandler: { result, error in
                completionHandler?(result, error)
            }
        }
    }
    
    
    /// 指定mac扫描连接
    /// - Parameters:
    ///   - mac: mac
    ///   - duration: 扫描时长
    public func scanAndConect(_ mac : String, _ duration: TimeInterval = 3){
        
        // CRPDiscovery中除了remotePeripheral其它数据区全是从广播数据中获取的
        
        CRPSmartRingSDK.sharedInstance.scan(duration) { [weak self] (newDiscoveries) in
            for discovery in newDiscoveries {
                if discovery.mac == mac {
                    self?.connectDiscovery = discovery
                    self?.interruptScanAndConnect(discovery)
                    return
                }
            }
        } completionHandler: { (result, error) in
            print("error = \(error)")
        }
    }
    
    /// 中断扫描
    public func interruptScan() {
        CRPSmartRingSDK.sharedInstance.interruptScan()
    }
    
    /// 连接某一设备
    /// - Parameter discovery: 设备
    public func connect(_ discovery: CRPSmartRing.CRPDiscovery) {
        let deviceInfo = DeviceInfo.current()
        deviceInfo.isBind = true
        deviceInfo.save()
        CRPSmartRingSDK.sharedInstance.connet(discovery)
    }
    
    /// 中断扫描并连接某一个设备
    /// - Parameter discovery: 设备
    public func interruptScanAndConnect(_ discovery: CRPSmartRing.CRPDiscovery) {
        self.interruptScan()
        self.connect(discovery)
    }
    
    /// 解除手环绑定
    public func remove(_ handler: ((_ state: CRPState) ->Void)?) {
        if self.bluetoothState != .poweredOn {
            self.deviceState = .disconnecting
            self.connectDiscovery =  nil
            self.currentBattery = nil
            handler?(.disconnecting)
            return
        }
        
        if self.deviceState == .connected {
            CRPSmartRingSDK.sharedInstance.remove { state, error in
                self.deviceState = state
                self.connectDiscovery =  nil
                self.currentBattery = nil
                handler?(state)
            }
        } else {
            handler?(self.deviceState)
        }
        
    }
    
    
    /// 重新连接
    public func reConnect() {
        CRPSmartRingSDK.sharedInstance.reConnet()
    }
    
    //MARK: - 查询点测状态
    public func getMeasurementState(handler: @escaping CRPSmartRing.measurementStateHandler) {
        
        CRPSmartRingSDK.sharedInstance.getMeasurementState { state, error in
            
            self.measuring = MeasureType.typeWithState(state)
            
            handler(state, error)
            
        }
    }
    
    //MARK: - 手环交互 -
    
    //MARK: - 同步时间
    /// 同步时间
    @objc public func setTime() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setTime()
        updateDateTimer = Date().timeIntervalSince1970
        
    }
    
   public func updateTime() {
        
        let date = Date().timeIntervalSince1970
        let scale = date - self.updateDateTimer
        if scale >= 2 * 3600 {
            self.setTime()
        }
    }
    
    
    //MARK: - 固件升级
    /// 查询⼿环当前固件版本
    /// - Parameter handler: String 当前固件版本
    public func getSoftver(_ handler: @escaping CRPSmartRing.stringHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getSoftver { value, error in
            handler(value, error)
        }
        
    }
    
    /// 查询新固件(通过传⼊当前版本的和mac地址获取是否有新版本固件可升级)
    /// - Parameters:
    ///   - version: 当前版本
    ///   - mac: mac地址
    ///   - handler: 是否有新版本固件可升级)
    public func checkLatest(_ version: String, _ mac: String, handler: @escaping CRPSmartRing.versionHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.checkLatest(version, mac) { info, error in
            handler(info, error)
        }
    }
    
    
    /// 查询序列号
    /// - Parameter handler: handle
    public func githash(handler: @escaping CRPSmartRing.stringHandler) {
        
        CRPSmartRingSDK.sharedInstance.getGitHashInfo(handler: handler)
        
    }
    
    
    public func startGoodixUpgradeFromFile(zipPath: String) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.startGoodixUpgradeFromFile(zipPath: zipPath)
    }
    
    
    public func checkDFUState(_ closure: @escaping CRPSmartRing.stringHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.checkDFUState { data, error in
            closure(data, error)
        }
    }
    
    
    public func stopUpgrade() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.stopUpgrade()
    }
    
    //MARK: - 查询设备电量
    /// 查询⼿环当前电量
    /// - Parameter closure:
    public func getBattery(_ handler: @escaping CRPSmartRing.intHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getBattery { value, error in
            handler(value, error)
        }
    }
    
    
    
    //MARK: - 用户信息
    
    /// 设置用户信息
    /// - Parameter profile: CRPSmartRing.ProfileModel
    public func setUserinfo(_ profile: CRPSmartRing.CRPUserInfoModel) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setUserinfo(profile)
    }
    
    /// 获取用户信息
    /// - Parameter handler:
    public func getUserinfo(_ handler: @escaping CRPSmartRing.profileHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getUserinfo(handler)
    }
    
    //MARK: - 久坐提醒
    
    /// 设置久坐提醒
    public func setActivityReminder(_ sitRemind: CRPSmartRing.CRPActivityReminderModel) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setActivityReminder(sitRemind)
    }
    
    /// 查询久坐提醒
    /// - Parameter handler:
    public func getActivityReminderInfo(_ handler: @escaping CRPSmartRing.sitRemindHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getActivityReminderInfo { sitRemind, error in
            handler(sitRemind, error)
        }
    }
    
    
    //MARK: - 关机
    
    /// 手环关机
    public func shutDown() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.shutDown()
    }
    
    //MARK: - 心率预警
    
    /// 设置⼼率预警
    /// - Parameter remind: ⼼率预警
    public func sendHeartRateRemind(_ remind: CRPSmartRing.CRPHRRemind) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setHeartRateRemind(remind)
    }
    
    /// 获取⼼率预警值
    /// - Parameter handler: ⼼率预警
    public func getHeartRateRemind(_ handler: @escaping CRPSmartRing.hrRemindHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getHeartRateRemind { model, error in
            handler(model, error)
        }
    }
    
    //MARK: - 恢复出厂设置
    
    /// 恢复出厂设置
    public func reset() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.reset()
    }
    
    //MARK: - HRV
    /// 开启定时测量⼼率
    /// 戒指⽀持24⼩时定时测量HRV，从0点0分开始测量，可以设置测量时间间隔（0为关闭,正数为开启,并设置为
    /// 测量量时间间隔为：正数 * 5分钟）
    /// - Parameter interval: 多少分间隔
    public func setTimingHRV(_ interval: Int) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setTimingHRV(interval)
    }
    
    /// 获取定时HRV测量状态
    /// - Parameter handler: int 测量间隔
    public func getTimingHRVInterval(_ handler: @escaping CRPSmartRing.intHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTimingHRVInterval(handler)
    }
    
    /// 获取单次HRV测量历史记录
    public func getHRVRecord(_ handler: @escaping CRPSmartRing.hrvRecordDataHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getHRVRecord { hrvRecordModels, error in
            handler(hrvRecordModels, error)
        }
    }
    
    /// 获取定时HRV测量数据
    public func getTimingHRV(_ day: Int, _ handler: @escaping CRPSmartRing.fullDayHRVRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTimingHRV(day) { model, error in
            handler(model, error)
        }
    }
    
    
    /// 主动测量HRV
    public func setStartHRV() {
        guard self.deviceState == .connected else {
            return
        }
        stopMeasuring()
        self.measuring = .HRV
        
        updateTime()
        CRPSmartRingSDK.sharedInstance.setStartHRV()
        
    }
    
    /// 停⽌测量HRV
    public func setStopHRV() {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.setStopHRV()
        // HRV
        self.measuring = .none
    }
    
    //MARK: - 压力
    
    /// 主动测量压力
    public func setStartStress() {
        guard self.deviceState == .connected else {
            return
        }
        stopMeasuring()
        self.measuring = .stress
        
        updateTime()
        CRPSmartRingSDK.sharedInstance.setStartStress()
    }
    
    /// 停⽌测量压力
    public func setStopStress() {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.setStopStress()
        self.measuring = .none
    }
    
    public func getStressRecord(_ handler: @escaping CRPSmartRing.stressRecordDataHandler) {
        
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getStressRecord { stressRecordModels, error in
            handler(stressRecordModels, error)
        }
        
    }
    
    //MARK: - 运动
    
    public func getTrainingSupportList(_ handler: @escaping CRPSmartRing.exerciseSupportListHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTrainingSupportList { list, error in
            
            handler(list, error)
        }
    }
    
    /// 设置运动模式
    /// - Parameter state:  运动模式
    public func setTraining(state: CRPSmartRing.CRPTrainingType, type: CRPSmartRing.CRPTrainingGoalType, goal: Int) {
        guard self.deviceState == .connected else {
            return
        }
        log.debug("发送锻炼的\(state)指令")
        if state == .end {
            self.measuring = .none
        }
        CRPSmartRingSDK.sharedInstance.setTraining(state: state, type: type, goal: goal)
        
    }
    
    
    public func getTrainingtRecordList() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTrainingtRecordList()
    }
    
    
    /// 获取相应锻炼详细数据(使⽤receiveTrainingList中返回的列表中的id去查询)
    /// - Parameters:
    ///   - id: id = 14 就是查询当前正在运动的
    ///   - closure: block
    public func getTrainingRecordData(id: Int, _ closure: @escaping CRPSmartRing.sportDetailHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTrainingRecordData(id: id) { data, error in
            closure(data, error)
        }
    }
    
    
    
    //MARK: - 睡眠
    /// 获取睡眠数据
    public func getSleepData(_ day: Int, _ handler: @escaping CRPSmartRing.sleepRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getSleepData(day) { model, error in
            handler(model, error)
        }
    }
    
    
    /// 获取睡眠活动量（1440个，一整天）
    /// - Parameters:
    ///   - day: 序号
    ///   - handler: block
    public func getSleepActivityArchiveData(_ day: Int, _ handler: @escaping CRPSmartRing.fullDayActivitysRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getActivityArchiveData(day, handler)
        
    }
    
    //MARK: - 体温
    public func setSleepTemperatureState(open: Bool) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setSleepTemperatureState(open: open)
        
    }
    
    
    /// 获取体温测量状态
    /// - Parameter handler: block
    public func getSleepTemperatureState(handler: @escaping CRPSmartRing.boolHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getSleepTemperatureState(handler: handler)
        
    }
    
    /// 获取体温测量数据
    /// - Parameters:
    ///   - day: 序号
    ///   - handler: block
    public func getSleepTemperatureData(day: Int, handler: @escaping CRPSmartRing.sleepTemperatureDataHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getSleepTemperatureData(day: day, handler: handler)
        
    }
    
    //MARK: - 活动步数
    public func getSteps() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getSteps()
    }
    
    /// 历史步数数据
    /// 注意： 这个接口返回的卡路里单位 是小卡 不是千卡
    public func getTrainingData(_ day: Int, _ handler: @escaping CRPSmartRing.exerciseRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTrainingData(day) { model, error in
            handler(model, error)
        }
    }
    
    
    /// 步数统计数据（每半小时一个值）
    /// - Parameters:
    ///   - day: 序号
    ///   - handler: handler
    public func getStepArchiveData(_ day: Int, _ handler: @escaping CRPSmartRing.fullDayStepsRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getStepArchiveData(day) { model, error in
            handler(model, error)
        }
    }
    
    
    //MARK: - 锻炼
    
    
    /// 锻炼状态检测
    /// - Parameter handler:
    public func getTraingingState(handler: @escaping CRPSmartRing.trainingStateHandler) {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.getTraingingState { type, state, error in
            
            if state == .unstarted {
                
                self.stopMeasuring()
                self.measuring = .none
            }
            
            handler(type, state, error)
            
        }
        
        
        CRPSmartRingSDK.sharedInstance.getTraingingState(handler)
        
    }
    
    /// 目标
    /// - Parameter goals: model
    public func setNormalTrainingGoal(_ goals: CRPSmartRing.CRPTrainingGoalsModel) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setNormalTrainingGoal(goals)
    }
    
    public func getNormalTrainingGoal(_ handler: @escaping CRPSmartRing.normalexerciseGoalDateHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getNormalTrainingGoal { exerciseGoalsModel, error in
            handler(exerciseGoalsModel, error)
        }
    }
    
    /// (state： 0(未提醒)，1(已提醒)收到锻炼中⽬标达成后需要使⽤setReceiveTrainingGoalReach⽅法通知戒指App已
    /// 经通知⽤户)
    public func receiveTrainingGoal(_ type: CRPTrainingGoalType, state: Int) {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.setReceiveTrainingGoalReach(type: type, state: 1)
        
    }
    
    
    public func setTrainingDayGoal(_ model: CRPSmartRing.CRPTrainingGoalStateModel, _ goals: CRPSmartRing.CRPTrainingGoalsModel) {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.setTrainingDayGoal(model, goals)
        
    }
    
    public func getTrainingDayGoal(_ handler: @escaping CRPSmartRing.exerciseGoalDateHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTrainingDayGoal { exerciseGoalsStateModel, exerciseGoalsModel, error in
            handler(exerciseGoalsStateModel, exerciseGoalsModel, error)
        }
    }
    
    //MARK: - 心率
    /// 开启定时测量⼼率
    /// 戒指⽀持24⼩时定时测量⼼率，从0点0分开始测量，可以设置测量时间间隔（0为关闭,正数为开启,并设置为
    /// 测量量时间间隔为：正数 * 5分钟）
    public func setTimingHeartRate(_ interval: Int) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setTimingHeartRate(interval)
    }
    
    
    /// 获取定时⼼率测量状态
    /// - Parameter handler: block
    public func getAutoHeartRateInterval(_ handler: @escaping CRPSmartRing.intHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTimingHeartRateInterval { value, error in
            handler(value, error)
        }
    }
    
    
    /// 获取定时测量⼼率数据
    /// - Parameters:
    ///   - day: 序号 0 代表今天， 1代表昨天 2代表前天 ...
    ///   - handler: block
    public func getTimingHeartRate(_ day: Int, _ handler: @escaping CRPSmartRing.fullDayHRRecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTimingHeartRate(day) { model, error in
            handler(model, error)
        }
    }
    
    /// 开启静态⼼率单次测量
    public func setStartSingleHR() {
        guard self.deviceState == .connected else {
            return
        }
        stopMeasuring()
        self.measuring = .heartRate
        updateTime()
        CRPSmartRingSDK.sharedInstance.setStartSingleHR()
    }
    
    /// 结束静态⼼率单次测量
    /// 结束单次测量量。测量量时间过短，会导致⽆⽆测量量数据。测量结果通过receiveHeartRate(_ heartRate: Int)回调。
    public func setStopSingleHR() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setStopSingleHR()
        self.measuring = .none
    }
    
    
    /// 获取单次⼼率测量历史记录(部分⼿环⽀持)
    /// - Parameter handler  单次⼼率测量历史记录
    public func getHeartRecordData(_ handler: @escaping CRPSmartRing.heartRecordDataHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getHeartRecordData { heartRecordData, error in
            handler(heartRecordData, error)
        }
    }
    
    //MARK: - 血氧
    /// 开始测量⾎氧。
    public func setStartSpO2() {
        guard self.deviceState == .connected else {
            return
        }
        stopMeasuring()
        self.measuring = .bloodOxyen
        updateTime()
        CRPSmartRingSDK.sharedInstance.setStartSpO2()
    }
    
    /// 停止测量⾎氧。
    /// 停⽌测量⾎氧，测量时间过短会导致⽆测量结果。结果通过receiveSpO2(_ o2: Int)回调。
    public func setStopSpO2() {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setStopSpO2()
        self.measuring = .none
    }
    
    /// 获取单次⾎氧测量历史记录
    public func getO2RecordData(_ handler: @escaping CRPSmartRing.o2RecordDataHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getO2RecordData { o2RecordModels, error in
            handler(o2RecordModels, error)
        }
    }
    
    /// 获取定时⾎氧测量状态
    public func getTimingO2Interval(_ handler: @escaping CRPSmartRing.intHandler) {
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.getTimingO2Interval(handler)
    }
    
    
    /// 开启定时测量血氧
    /// 戒指⽀持24⼩时定时测量⾎氧，从0点0分开始测量，可以设置测量时间间隔（0为关闭,正数为开启,并设置为
    /// 测量量时间间隔为：正数 * 5分钟）
    public func setTimingO2(_ interval: Int){
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.setTimingO2(interval)
    }
    
    /// 获取定时⾎氧数据
    public func getTimingO2(_ day: Int, _ handler: @escaping CRPSmartRing.fullDayO2RecordHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getTimingO2(day) { model, error in
            handler(model, error)
        }
    }
    
    
    //MARK: - mac -
    /// 获取mac地址？
    /// - Parameter handler:
    public func getMac(_ handler: @escaping CRPSmartRing.stringHandler) {
        guard self.deviceState == .connected else {
            return
        }
        CRPSmartRingSDK.sharedInstance.getMac { data, error in
            handler(data, error)
        }
    }
    
    //MARK: - 获取戒指颜色尺寸信息
    public func getRingInfo(_ handler: @escaping CRPSmartRing.ringInfoHandler) {
        
        guard self.deviceState == .connected else {
            return
        }
        
        CRPSmartRingSDK.sharedInstance.getRingInfo(handler: handler)
        
    }
    
    //MARK: - 检查是否佩戴戒指
    /// 设置 戒指是否佩戴的监听 通过receiveWearState(_ state: Int)返回结果
    public func setWearStateChangeListener() {
        CRPSmartRingSDK.sharedInstance.getWearState()
        
    }
    
}

//MARK: - SDK的回调

extension BluetoothManager: CRPManagerDelegate {
    
    
    // 固件升级
    public func receiveOTA(_ state: CRPOTAState, _ progress: Int) {
        
        let model = NKReceiveUpgredeModel(state: state, progress: progress)
        NotificationCenter.default.post(name: .kReceiveUpgredeNotification, object: nil, userInfo: ["result": model])
        
    }
    
    
    /// 返回当前的⼿环的连接状态
    /// - Parameter closure: CRPState
    public func didState(_ state: CRPSmartRing.CRPState) {
        
        //        // CRPDiscovery中除了remotePeripheral其它数据区全是从广播数据中获取的
        self.connectDiscovery = CRPSmartRingSDK.sharedInstance.currentCRPDiscovery
        self.deviceState = state
        
        log.debug("---")
        log.debug("连接状态：\(state.rawValue)")

        switch state {
        case .unbind:
            log.debug("未绑定")
        case .connecting:
            log.debug("正在连接")
        case .connected:
            log.debug("连接成功")
        case .disconnecting:
            log.debug("正在断开")
        case .disconnected:
            log.debug("已经断开")
        case .syncing:
            log.debug("同步中")
        case .syncSuccess:
            log.debug("同步成功")
        case .syncError:
            log.debug("同步出错")
        @unknown default:
            break
        }
        
        log.debug("---")
        
        
        //连接成功之后，判断数据库里面的deviceInfo的isbind，如果false那么就remove，同时界面那个
        let deviceInfo = DeviceInfo.current()
        
        if state == .connected {
            
            // 除了首次连接，其他连接如果解除绑定了，就不能在连接
            if deviceInfo.isFirstConnect == false && deviceInfo.isBind == false {
                self.remove { state in
                    log.debug("上一次是断开蓝牙解除绑定，主动解绑")
                }
                return
            }
            // 同步时间
            self.setTime()
            
            
            #if DEBUG
            
            CRPSmartRingSDK.sharedInstance.getRebootTimes { value, error in
                
                log.debug("重启次数： \(value)")
                
            }
            #endif
            
            // 电量查询，会主动推送电量变化
            self.getBattery { value, error in
                
                self.currentBattery = value
                NotificationCenter.default.post(name: .kBatteryNotification, object: nil, userInfo: ["result": value])
                
                // 在充电状态如果还有点测的，需要结束
                if value > 100 && self.measuring != .none {
                    self.stopMeasuring()
                }
                
            }
            
            // 是否佩戴
            self.setWearStateChangeListener()
            
            // 久坐提醒
            self.getActivityReminderInfo { sitRemind, error in
                
                self.deviceReminderModel = sitRemind
                var prefileModel = UserCacheManagement.userInfo()
                prefileModel.sitRemind = sitRemind.open
                UserCacheManagement.updateUserInfo(prefileModel)
                
                
            }
            
            // 测量中状态检测
            self.getMeasurementState { state, error in
                
            }
            
            NotificationCenter.default.post(name: .kDeviceStateNotification, object: nil, userInfo: ["result": state])
            
        } else if state == .disconnected {
            
            NotificationCenter.default.post(name: .kDeviceStateNotification, object: nil, userInfo: ["result": state])
            
        }
        
       
    }
    
    /// 返回当前蓝⽛状态
    /// - Parameter closure: CRPBluetoothState
    public func didBluetoothState(_ state: CRPSmartRing.CRPBluetoothState) {
        self.bluetoothState = state
        self.deviceState = .disconnected
        NotificationCenter.default.post(name: .kBluetoothStateNotification, object: nil, userInfo: ["result": state])
    }
    
    /// 接收实时的运动计步数据
    /// - Parameter model: TrainingModel
    public func receiveSteps(_ model: CRPSmartRing.CRPStepModel) {
        NotificationCenter.default.post(name: .kReceiveStepsNotification, object: nil, userInfo: ["result": model])
        
    }
    
    /// 接收⼼率测量结果(单次测量⼼率)
    public func receiveHeartRate(_ heartRate: Int) {
        
        self.measuring = .none
        NotificationCenter.default.post(name: .kReceiveSingleHeartRateNotification, object: nil, userInfo: ["result": heartRate])
        
        
    }
    
    /// 接收实时⼼率数据(⼀般只⽤于显示不⽤于存储，部分⼿环⽀持返回实时RRI数据)
    public func receiveRealTimeHeartRate(_ heartRate: Int) {
        let model = ReceiveRealTimeHeartRateModel(heartRate: heartRate)
        NotificationCenter.default.post(name: .kReceiveRealTimeHeartRateNotification, object: nil, userInfo: ["result": model])
    }
    
    
    /// 接收HRV
    /// - Parameter hrv: hrv value
    public func receiveHRV(_ hrv: Int) {
        
        self.measuring = .none
        NotificationCenter.default.post(name: .kReceiveSingleHRVNotification, object: nil, userInfo: ["result": hrv])
        
    }
    
    /// 接收压力
    /// - Parameter stress: 压力
    public func receiveStress(_ stress: Int) {
        self.measuring = .none
        NotificationCenter.default.post(name: .kReceiveSingleStressNotification, object: nil, userInfo: ["result": stress])
        
    }
    
    
    /// 接收⾎氧测量结果
    /// - Parameter closure: Int
    public func receiveSpO2(_ o2: Int) {
        
        self.measuring = .none
        NotificationCenter.default.post(name: .kReceiveSingleSpO2Notification, object: nil, userInfo: ["result": o2])
    }
    
    public func receiveUpgrede(_ state: CRPOTAState, _ progress: Int) {
        let model = NKReceiveUpgredeModel(state: state, progress: progress)
        NotificationCenter.default.post(name: .kReceiveUpgredeNotification, object: nil, userInfo: ["result": model])
    }
    
    public func receiveTrainingList(_ list: [CRPTrainingRecord]) {
        NotificationCenter.default.post(name: .kReceiveSportListNotification, object: nil, userInfo: ["result": list])
    }
    
    // 运动 模式
    public func receiveTrainingState(_ state: CRPTrainingType) {
        NotificationCenter.default.post(name: .kReceiveSportStateInfoNotification, object: nil, userInfo: ["result": state])
    }
    
    /// 戒指是否佩戴的监听
    public func receiveWearState(_ state: Int) {
        wearState = state == 1
        
        deWearStateNotifactions()
   
        NotificationCenter.default.post(name: .kReceiveWearStateNotification, object: nil, userInfo: ["result": state])
        
        
        
    }
    
    /// 久坐提醒监听
    public func receiveActivityReminder(isReminder: Int, wearState: Int, time: Int, step: Int) {
        
        let remiderModel = ReminderModel(isReminder: isReminder, wearState: wearState, time: time, step: step)
        
        NotificationCenter.default.post(name: .kActivityReminderInfoNotification, object: nil, userInfo: ["result": remiderModel])
        
    }
    
    public func deWearStateNotifactions() {
        
        if self.measuring == .none || self.wearState == true {
            return
        }
        
        switch measuring {
            
        case .none:
            return
        case .HRVAndStress:
            
            NotificationCenter.default.post(name: .kReceiveSingleHRVNotification, object: nil, userInfo: ["result": 0])
            NotificationCenter.default.post(name: .kReceiveSingleStressNotification, object: nil, userInfo: ["result": 0])
            break
            
        case .HRV:
            NotificationCenter.default.post(name: .kReceiveSingleHRVNotification, object: nil, userInfo: ["result": 0])
            break
        case .stress:
            NotificationCenter.default.post(name: .kReceiveSingleStressNotification, object: nil, userInfo: ["result": 0])
            break
        case .heartRate:
            NotificationCenter.default.post(name: .kReceiveSingleHeartRateNotification, object: nil, userInfo: ["result": 0])
            break
        case .trainingHeartRate:
            
            return
            
        case .bloodOxyen:
            NotificationCenter.default.post(name: .kReceiveSingleSpO2Notification, object: nil, userInfo: ["result": 0])
            break
        }
        
        self.stopMeasuring()
        self.measuring = .none
        
        
    }
    
    
    
    
    /// 强制结束本次测量
    public func stopMeasuring() {
        
        if self.measuring == .none {
            return
        }
        
        switch self.measuring {
            
        case .none:
            break
        case .HRVAndStress:
            self.setStopStress()
            break
        case .HRV:
            self.setStopHRV()
            break
        case .stress:
            self.setStopStress()
            break
        case .heartRate:
            self.setStopSingleHR()
            break
        case .bloodOxyen:
            self.setStopSpO2()
            break
        case .trainingHeartRate:
            self.measuring = .none
            break
            
            
        }
        
    }
    
}

public struct ReminderModel {
    
    /// 0：App不需要提醒，1：App需要提醒
    public var isReminder: Int
    
    /// 00:未佩戴， 01：佩戴)
    public var wearState: Int
    public var time: Int
    public var step: Int
    
}


open class ReceiveRealTimeHeartRateModel: HandyJSON {
    
    //
    public var heartRate: Int = 0
    
    public required init() {
        
    }
    
    public required init(heartRate: Int = 0) {
        self.heartRate = heartRate
    }
}

open class ReceiveHRVModel: HandyJSON {
    public var hrv: Int = 0
    public var stress: Int = 0
    
    public required init() {
        
    }
    
    public required init(hrv: Int = 0, stress: Int = 0) {
        self.hrv = hrv
        self.stress = stress
    }
}


open class NKReceiveUpgredeModel: HandyJSON {
    
    //状态
    public var state: CRPOTAState?
    
    //进度
    public var progress: Int = 0
    
    public required init() {
        
    }
    
    public required init(state: CRPOTAState?, progress: Int = 0) {
        self.state = state
        self.progress = progress
    }
}

extension BluetoothManager {
    
    public enum MeasureType {
        
        /// 不测量任何
        case none
        
        /// 测量HRV和压力2个数据
        case HRVAndStress
        
        /// 测量HRV
        case HRV
        
        /// 测量压力
        case stress
        
        /// 测量心率
        case heartRate
        
        /// 测量运动心率
        case trainingHeartRate
        
        /// 测量血氧
        case bloodOxyen
        
        
        public static func typeWithState(_ state: CRPMeasurementState) ->MeasureType {
            
            switch state {
                
            case .notMeasured:
                return .none
            case .respirationHR:
                return .none
            case .trainingHR:
                return .trainingHeartRate
            case .staticHR:
                return .heartRate
            case .bp:
                return .none
            case .spO2:
                return .bloodOxyen
            case .ecg:
                return .none
            case .temperature:
                return .none
            case .hrv:
                return .HRV
            case .combination:
                return .none
            case .factoryTest:
                return .none
            case .stress:
                return .stress
            @unknown default:
                return .none
            }
            
        }
        
        
    }
    
}

extension BluetoothManager: CBCentralManagerDelegate {
    
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        
    }
    
    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        let rssiInt = RSSI.intValue
        let data = advertisementData as [String: AnyObject]
        
        let discovery = CRPDiscovery(advertisementData: data, remotePeripheral: peripheral, RSSI: rssiInt)
        guard let localName = discovery.localName, let mac = discovery.mac else { return }
        return
        
//        print(localName)
        
        if localName != "MoRing" {
            return
        }
        
        self.scanAndConect(mac)
        
    }
    
    
}






